package com.example.message.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.message.entity.Message;
import com.example.message.entity.MessageReceive;
import com.example.message.enums.MessageType;
import com.example.message.enums.TargetType;
import com.example.message.service.MessageService;
import com.example.message.vo.MessageVO;
import com.example.project.entity.Issue;
import com.example.project.entity.Journal;
import com.example.project.entity.JournalDetail;
import com.example.project.entity.Role;
import com.example.project.entity.User;
import com.example.project.entity.Watcher;
import com.example.project.service.CommonService;
import com.example.project.service.JournalDetailService;
import com.example.project.service.JournalService;
import com.example.project.service.impl.BaseServiceImpl;
import com.example.project.utils.DateUtils;
import com.example.project.utils.StringUtils;

/**
 * 通知服务实现类
 */
@Service
public class MessageServiceImpl extends BaseServiceImpl implements MessageService {

	@Autowired
	private CommonService commonService;

	@Autowired
	private JournalService journalService;

	@Autowired
	private JournalDetailService journalDetailService;

	/**
	 * 发送通知
	 * 
	 * @param message 通知实体对象
	 * @return 发送是否成功
	 */
	@Override
	@Transactional
	public int sendMessage(Message message) {
		// 保存通知主记录
		int saveResult = messageMapper.insertMessage(message);
		if (saveResult == 0) {
			return saveResult;
		}

		// 根据目标类型创建接收记录
		List<MessageReceive> receiveList = createReceiveRecords(message);
		if (receiveList.isEmpty()) {
			return saveResult;
		}

		// 批量保存接收记录
		return messageReceiveMapper.batchInsert(receiveList);
	}

	/**
	 * 使用模板发送通知
	 * 
	 * @param message 通知实体对象
	 * @return 发送是否成功
	 */
	@Override
	public int sendMessageByTemplate(Message message) {
		// 使用模板发送通知
		return sendMessage(message);
	}

	/**
	 * 查询通知列表
	 * 
	 * @param queryDTO 查询条件
	 * @return 通知列表
	 */
	@Override
	public List<Message> selectMessageList(Message message) {
		// TODO: 实现通知列表查询
		Page<Message> page = new Page<>(1, Integer.MAX_VALUE);
		List<Message> messages = messageMapper.selectList(page, message);
		return messages;
	}

	/**
	 * 根据ID查询通知详情
	 * 
	 * @param noticeId 通知ID
	 * @return 通知详情
	 */
	@Override
	public MessageVO selectMessageById(Long messageId) {
		if (messageId == null) {
			return null;
		}

		// 查询通知基本信息
		Message message = messageMapper.findById(messageId);
		if (message == null || message.getDelFlag() == 1) {
			return null;
		}

		// 转换为VO对象
		MessageVO messageVO = convertToVO(message);

		// 查询接收记录信息
		List<MessageReceive> receiveList = messageReceiveMapper.findListByMessageId(messageId);

		// 设置接收记录统计信息
		if (receiveList != null && !receiveList.isEmpty()) {
			long totalCount = receiveList.size();
			long readCount = receiveList.stream().filter(r -> r.getReadStatus() == 1).count();
			long unreadCount = totalCount - readCount;
			long handledCount = receiveList.stream().filter(r -> r.getHandleStatus() == 1).count();

			messageVO.setReadStatus(readCount > 0 ? 1 : 0);
			messageVO.setReadTime(receiveList.stream().filter(r -> r.getReadTime() != null)
					.map(MessageReceive::getReadTime).max(LocalDateTime::compareTo).orElse(null));
			messageVO.setHandleStatus(handledCount > 0 ? 1 : 0);
			messageVO.setHandleTime(receiveList.stream().filter(r -> r.getHandleTime() != null)
					.map(MessageReceive::getHandleTime).max(LocalDateTime::compareTo).orElse(null));

			markAsRead(messageId, getUserId());
		}

		return messageVO;
	}

	/**
	 * 批量删除通知
	 * 
	 * @param noticeIds 通知ID数组
	 * @return 删除是否成功
	 */
	@Override
	public boolean deleteMessageByIds(Long[] noticeIds) {
		// TODO: 实现批量删除通知
		return false;
	}

	/**
	 * 获取用户通知列表
	 * 
	 * @param userId     用户ID
	 * @param noticeType 通知类型
	 * @param readStatus 阅读状态
	 * @return 用户通知列表
	 */
	@Override
	public List<Message> getUserMessageList(Long userId, Integer noticeType, Integer readStatus) {
		// 使用新的Mapper方法查询通知列表
		Page<Message> page = new Page<>(1, Integer.MAX_VALUE);
		return messageMapper.selectMessageByReceiverId(page, userId, noticeType, readStatus);
	}

	/**
	 * 更新通知信息
	 * 
	 * @param message 通知实体对象
	 * @return 更新是否成功
	 */
	@Override
	@Transactional
	public boolean updateMessage(Message message) {
		if (message == null || message.getMessageId() == null) {
			return false;
		}

		// 检查通知是否存在
		Message existingMessage = messageMapper.findById(message.getMessageId());
		if (existingMessage == null || existingMessage.getDelFlag() == 1) {
			return false;
		}

		// 更新通知记录
		int updateResult = messageMapper.updateMessage(message);
		return updateResult > 0;
	}

	/**
	 * 标记通知为已读
	 * 
	 * @param receiveId 接收记录ID
	 * @param userId    用户ID
	 * @return 标记是否成功
	 */
	@Override
	public boolean markAsRead(Long messageId, Long userId) {
		MessageReceive messageReceive = messageReceiveMapper.findByMessageIdAndReceiverId(messageId, userId);
		if (messageReceive == null || !messageReceive.getReceiverId().equals(userId)) {
			return false;
		}
		messageReceive.setReadStatus(1); // 已读
		messageReceive.setReadTime(LocalDateTime.now());
		return messageReceiveMapper.updateById(messageReceive) > 0;
	}

	/**
	 * 批量标记通知为已读
	 * 
	 * @param receiveIds 接收记录ID列表
	 * @param userId     用户ID
	 * @return 批量标记是否成功
	 */
	@Override
	public boolean batchMarkAsRead(List<Long> receiveIds, Long userId) {
		if (receiveIds == null || receiveIds.isEmpty()) {
			return false;
		}

		List<MessageReceive> receiveList = messageReceiveMapper.selectBatchIds(receiveIds);
		if (receiveList.isEmpty()) {
			return false;
		}

		for (MessageReceive messageReceive : receiveList) {
			if (messageReceive.getReceiverId().equals(userId)) {
				messageReceive.setReadStatus(1);
				messageReceive.setReadTime(LocalDateTime.now());
				messageReceiveMapper.updateById(messageReceive);
			}
		}
		return true;
	}

	/**
	 * 处理通知
	 * 
	 * @param receiveId    接收记录ID
	 * @param userId       用户ID
	 * @param handleStatus 处理状态
	 * @param handleRemark 处理备注
	 * @return 处理是否成功
	 */
	@Override
	public boolean handleMessage(Long receiveId, Long userId, Integer handleStatus, String handleRemark) {
		MessageReceive messageReceive = messageReceiveMapper.findById(receiveId);
		if (messageReceive == null || !messageReceive.getReceiverId().equals(userId)) {
			return false;
		}
		messageReceive.setHandleStatus(handleStatus);
		messageReceive.setHandleRemark(handleRemark);
		messageReceive.setHandleTime(LocalDateTime.now());
		return messageReceiveMapper.updateById(messageReceive) > 0;
	}

	/**
	 * 查看通知详情
	 * 
	 * @param receiveId 接收记录ID
	 * @param userId    用户ID
	 * @return 通知详情
	 */
	@Override
	public MessageVO viewMessage(Long receiveId, Long userId) {
		// TODO: 实现查看通知详情
		return new MessageVO();
	}

	// 以下为原有方法实现
	/**
	 * 发送通知给指定用户
	 * 
	 * @param userId     用户ID
	 * @param title      通知标题
	 * @param content    通知内容
	 * @param noticeType 通知类型
	 * @return 发送是否成功
	 */
	@Override
	public int sendToUser(Long userId, String title, String content, Integer noticeType) {
		Message message = new Message();
		message.setTitle(title);
		message.setContent(content);
		message.setMessageType(noticeType);
		message.setTargetType(TargetType.USER.getCode());
		message.setTargetIds("[" + userId + "]");
		message.setCreateTime(LocalDateTime.now());
		return sendMessage(message);
	}

	/**
	 * 发送通知给指定角色
	 * 
	 * @param roleId     角色ID
	 * @param title      通知标题
	 * @param content    通知内容
	 * @param noticeType 通知类型
	 * @return 发送是否成功
	 */
	@Override
	public int sendToRole(Long roleId, String title, String content, Integer noticeType) {
		Message message = new Message();
		message.setTitle(title);
		message.setContent(content);
		message.setMessageType(noticeType);
		message.setTargetType(TargetType.ROLE.getCode());
		message.setTargetIds("[" + roleId + "]");
		message.setCreateTime(LocalDateTime.now());
		return sendMessage(message);
	}

	/**
	 * 发送通知给指定部门
	 * 
	 * @param deptId     部门ID
	 * @param title      通知标题
	 * @param content    通知内容
	 * @param noticeType 通知类型
	 * @return 发送是否成功
	 */
	@Override
	public int sendToDept(Long deptId, String title, String content, Integer noticeType) {
		Message message = new Message();
		message.setTitle(title);
		message.setContent(content);
		message.setMessageType(noticeType);
		message.setTargetType(TargetType.DEPT.getCode());
		message.setTargetIds("[" + deptId + "]");
		message.setCreateTime(LocalDateTime.now());
		return sendMessage(message);
	}

	/**
	 * 发送通知给指定岗位
	 * 
	 * @param positionId 岗位ID
	 * @param title      通知标题
	 * @param content    通知内容
	 * @param noticeType 通知类型
	 * @return 发送是否成功
	 */
	@Override
	public int sendToPosition(Long positionId, String title, String content, Integer noticeType) {
		Message message = new Message();
		message.setTitle(title);
		message.setContent(content);
		message.setMessageType(noticeType);
		message.setTargetType(TargetType.POSITION.getCode());
		message.setTargetIds("[" + positionId + "]");
		message.setCreateTime(LocalDateTime.now());
		return sendMessage(message);
	}

	/**
	 * 发送通知给全体用户
	 * 
	 * @param title      通知标题
	 * @param content    通知内容
	 * @param noticeType 通知类型
	 * @return 发送是否成功
	 */
	@Override
	public int sendToAll(String title, String content, Integer noticeType) {
		Message message = new Message();
		message.setTitle(title);
		message.setContent(content);
		message.setMessageType(noticeType);
		message.setTargetType(TargetType.ALL.getCode());
		message.setTargetIds("[]");
		message.setCreateTime(LocalDateTime.now());
		return sendMessage(message);
	}

	/**
	 * 使用模板发送通知
	 * 
	 * @param templateCode 模板代码
	 * @param params       模板参数
	 * @param targetType   目标类型
	 * @param targetIds    目标ID列表
	 * @return 发送是否成功
	 */
	@Override
	public int sendByTemplate(String templateCode, Map<String, Object> params, Integer targetType, String targetIds) {
		// TODO: 实现模板发送逻辑
		return 0;
	}

	/**
	 * 撤销通知
	 * 
	 * @param noticeId 通知ID
	 * @return 撤销是否成功
	 */
	@Override
	public boolean revokeMessage(Long noticeId) {
		Message message = messageMapper.findById(noticeId);
		if (message == null) {
			return false;
		}
		message.setStatus(2); // 撤销状态
		return updateMessage(message);
	}

	/**
	 * 获取用户未读通知数量
	 * 
	 * @param userId 用户ID
	 * @return 未读通知数量
	 */
	@Override
	public Long getUnreadCount(Long userId) {
		return messageReceiveMapper.findTotalByReceiverIdAndReadStatus(userId, 0);
	}

	/**
	 * 获取新通知（用于右下角弹窗）
	 * 
	 * @param userId        用户ID
	 * @param lastCheckTime 上次检查时间
	 * @return 新通知列表
	 */
	@Override
	public List<MessageVO> getNewNotifications(Long userId, Long lastCheckTime) {
		List<MessageReceive> receiveList = messageReceiveMapper.findNewByReceiverIdAfterTime(userId, lastCheckTime);
		List<MessageVO> result = new ArrayList<>();

		for (MessageReceive receive : receiveList) {
			Message message = messageMapper.findById(receive.getMessageId());
			if (message != null) {
				MessageVO vo = convertToVO(message, receive);
				result.add(vo);
			}
		}

		return result;
	}

	/**
	 * 将Message和MessageReceive转换为MessageVO
	 */
	private MessageVO convertToVO(Message message, MessageReceive receive) {
		MessageVO vo = new MessageVO();
		vo.setMessageId(message.getMessageId());
		vo.setReceiveId(receive.getReceiveId());
		vo.setTitle(message.getTitle());
		vo.setContent(message.getContent());
		vo.setMessageType(message.getMessageType());
		vo.setPriority(message.getPriority());
		vo.setSenderId(message.getSenderId());
		vo.setSenderName(message.getSenderName());
		vo.setSendTime(message.getSendTime());
		vo.setReadStatus(receive.getReadStatus());
		vo.setHandleStatus(receive.getHandleStatus());

		// 设置业务URL，根据业务类型和业务ID生成
		if (message.getBusinessType() != null && message.getBusinessId() != null) {
			vo.setUrl(generateBusinessUrl(message.getBusinessType(), message.getBusinessId()));
		} else {
			vo.setUrl("/system/message/receive/view/" + receive.getReceiveId());
		}

		return vo;
	}

	/**
	 * 根据业务类型和业务ID生成业务URL
	 */
	private String generateBusinessUrl(String businessType, String businessId) {
		// 这里可以根据业务类型返回不同的URL
		// 例如：问题审批、任务分配等
		return "/system/message/receive/view/" + businessId;
	}

	/**
	 * 创建通知接收记录
	 * 
	 * @param message 通知实体对象
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createReceiveRecords(Message message) {
		List<MessageReceive> receiveList = new ArrayList<>();
		Integer targetType = message.getTargetType();
		String targetIds = message.getTargetIds();

		if (targetIds == null || targetIds.trim().isEmpty()) {
			return receiveList;
		}

		// 解析目标ID列表
		List<Long> targetIdList = parseTargetIds(targetIds);
		if (targetIdList.isEmpty()) {
			return receiveList;
		}

		// 根据目标类型创建接收记录
		TargetType type = TargetType.getByCode(targetType);
		if (type != null) {
			switch (type) {
			case USER:
				receiveList = createUserReceiveRecords(message, targetIdList);
				break;
			case ROLE:
				receiveList = createRoleReceiveRecords(message, targetIdList);
				break;
			case DEPT:
				receiveList = createDeptReceiveRecords(message, targetIdList);
				break;
			case POSITION:
				receiveList = createPositionReceiveRecords(message, targetIdList);
				break;
			case ALL:
				receiveList = createAllUserReceiveRecords(message);
				break;
			default:
				break;
			}
		}

		return receiveList;
	}

	/**
	 * 解析目标ID字符串
	 * 
	 * @param targetIds 目标ID字符串
	 * @return 目标ID列表
	 */
	private List<Long> parseTargetIds(String targetIds) {
		try {
			// 移除方括号和空格，然后按逗号分割
			String cleanIds = targetIds.replaceAll("[\\[\\]\\s]", "");
			if (cleanIds.isEmpty()) {
				return new ArrayList<>();
			}

			return Arrays.stream(cleanIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Long::valueOf)
					.collect(Collectors.toList());
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}

	/**
	 * 为用户创建接收记录
	 * 
	 * @param message 通知实体对象
	 * @param userIds 用户ID列表
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createUserReceiveRecords(Message message, List<Long> userIds) {
		List<MessageReceive> receiveList = new ArrayList<>();
		List<User> userList = userMapper.selectBatchIds(userIds);
		for (User user : userList) {
			if (user != null) {
				Long userId = user.getUserId();
				MessageReceive receive = createMessageReceive(message, userId, user.getUserName(), user.getDeptId(),
						user.getDept() != null ? user.getDept().getDeptName() : null);
				receiveList.add(receive);
			}
		}
		String targetNames = userList.stream().map(User::getLoginName).collect(Collectors.joining(","));
		message.setTargetNames(targetNames);
		messageMapper.updateMessage(message);

		return receiveList;
	}

	/**
	 * 为角色创建接收记录
	 * 
	 * @param message 通知实体对象
	 * @param roleIds 角色ID列表
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createRoleReceiveRecords(Message message, List<Long> roleIds) {
		List<MessageReceive> receiveList = new ArrayList<>();

		for (Long roleId : roleIds) {
			// 查询该角色下的所有用户
			List<User> users = userMapper.selectUserAll().stream().filter(user -> {
				List<Role> roles = user.getRoles();
				return roles != null && roles.stream().anyMatch(role -> roleId.equals(role.getRoleId())
						&& "0".equals(role.getDelFlag()) && "0".equals(role.getStatus()));
			}).collect(Collectors.toList());

			for (User user : users) {
				if ("0".equals(user.getDelFlag()) && "0".equals(user.getStatus())) {
					MessageReceive receive = createMessageReceive(message, user.getUserId(), user.getUserName(),
							user.getDeptId(), user.getDept() != null ? user.getDept().getDeptName() : null);
					receiveList.add(receive);
				}
			}
		}

		return receiveList;
	}

	/**
	 * 为部门创建接收记录
	 * 
	 * @param message 通知实体对象
	 * @param deptIds 部门ID列表
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createDeptReceiveRecords(Message message, List<Long> deptIds) {
		List<MessageReceive> receiveList = new ArrayList<>();

		for (Long deptId : deptIds) {
			// 查询该部门下的所有用户
			User queryUser = new User();
			queryUser.setDeptId(deptId);
			List<User> users = userMapper.selectUserList(null, queryUser);

			for (User user : users) {
				if ("0".equals(user.getDelFlag()) && "0".equals(user.getStatus())) {
					MessageReceive receive = createMessageReceive(message, user.getUserId(), user.getUserName(),
							user.getDeptId(), user.getDept() != null ? user.getDept().getDeptName() : null);
					receiveList.add(receive);
				}
			}
		}

		return receiveList;
	}

	/**
	 * 为岗位创建接收记录
	 * 
	 * @param message     通知实体对象
	 * @param positionIds 岗位ID列表
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createPositionReceiveRecords(Message message, List<Long> positionIds) {
		List<MessageReceive> receiveList = new ArrayList<>();

		for (Long positionId : positionIds) {
			// 查询该岗位下的所有用户
			List<User> users = userMapper.selectUserAll().stream().filter(user -> {
				Long[] postIds = user.getPostIds();
				return postIds != null && Arrays.stream(postIds).anyMatch(id -> positionId.equals(id));
			}).collect(Collectors.toList());

			for (User user : users) {
				if ("0".equals(user.getDelFlag()) && "0".equals(user.getStatus())) {
					MessageReceive receive = createMessageReceive(message, user.getUserId(), user.getUserName(),
							user.getDeptId(), user.getDept() != null ? user.getDept().getDeptName() : null);
					receiveList.add(receive);
				}
			}
		}

		return receiveList;
	}

	/**
	 * 为全体用户创建接收记录
	 * 
	 * @param message 通知实体对象
	 * @return 接收记录列表
	 */
	private List<MessageReceive> createAllUserReceiveRecords(Message message) {
		List<MessageReceive> receiveList = new ArrayList<>();

		// 查询所有正常状态的用户
		List<User> users = userMapper.selectUserAll().stream()
				.filter(user -> "0".equals(user.getDelFlag()) && "0".equals(user.getStatus()))
				.collect(Collectors.toList());

		for (User user : users) {
			MessageReceive receive = createMessageReceive(message, user.getUserId(), user.getUserName(),
					user.getDeptId(), user.getDept() != null ? user.getDept().getDeptName() : null);
			receiveList.add(receive);
		}

		return receiveList;
	}

	/**
	 * 创建单个接收记录
	 * 
	 * @param message      通知实体对象
	 * @param receiverId   接收人ID
	 * @param receiverName 接收人姓名
	 * @param deptId       部门ID
	 * @param deptName     部门名称
	 * @return 接收记录
	 */
	private MessageReceive createMessageReceive(Message message, Long receiverId, String receiverName, Long deptId,
			String deptName) {
		MessageReceive receive = new MessageReceive();
		receive.setMessageId(message.getMessageId());
		receive.setReceiverId(receiverId);
		receive.setReceiverName(receiverName);
		receive.setDeptId(deptId);
		receive.setDeptName(deptName);
		receive.setReadStatus(0); // 未读
		receive.setHandleStatus(0); // 未处理
		receive.setCreateTime(LocalDateTime.now());
		receive.setUpdateTime(LocalDateTime.now());
		receive.setDelFlag(0);

		return receive;
	}

	/**
	 * 将Message实体转换为MessageVO视图对象
	 * 
	 * @param message 通知实体
	 * @return 通知视图对象
	 */
	private MessageVO convertToVO(Message message) {
		if (message == null) {
			return null;
		}

		MessageVO messageVO = new MessageVO();
		messageVO.setMessageId(message.getMessageId());
		messageVO.setTitle(message.getTitle());
		messageVO.setContent(message.getContent());
		messageVO.setMessageType(message.getMessageType());
		messageVO.setPriority(message.getPriority());
		messageVO.setSendTime(message.getSendTime());
		messageVO.setSenderName(message.getSenderName());
		messageVO.setExpireTime(message.getExpireTime());

		// 设置通知类型描述
		com.example.message.enums.MessageType messageType = com.example.message.enums.MessageType
				.getByCode(message.getMessageType());
		if (messageType != null) {
			messageVO.setMessageTypeDesc(messageType.getDesc());
		}

		// 设置优先级描述
		com.example.message.enums.PriorityType priorityType = com.example.message.enums.PriorityType
				.getByCode(message.getPriority());
		if (priorityType != null) {
			messageVO.setPriorityDesc(priorityType.getDesc());
		}

		return messageVO;
	}

	@Override
	public List<Message> findListByReceiverId(Long receiverId, Integer messageType, Integer readStatus, int size) {
		// TODO Auto-generated method stub
		return messageMapper.findListByReceiverId(receiverId, messageType, readStatus, size);
	}

	@Override
	public int sendIssueMessage(Issue issue) {
		// 发送消息
		String targetIds = String.valueOf(getUserId());
		Long assignedToId = issue.getAssignedToId();
		if (assignedToId != null && assignedToId != 0) {
			targetIds += "," + assignedToId;
		}
		Long authorId = issue.getAuthorId();
		if (authorId != null) {
			targetIds += "," + authorId;
		}
		// 查询关注人
		List<Watcher> watcherList = watcherMapper.selectWatchersByObject("Issue", issue.getId());
		if (!watcherList.isEmpty()) {
			for (Watcher watcher : watcherList) {
				targetIds += "," + watcher.getUserId();
			}
		}
		return sendMessage(issue, targetIds);
	}

	private int sendMessage(Issue issue, String targetIds, String... targetNameArr) {
		// TODO Auto-generated method stub
		// 指派给用户ID
		int result = 0;
		if (StringUtils.isNotEmpty(targetIds)) {
			// 获取管理源信息
			User Administrator = commonService.getAdministrator();

			Message message = new Message();
			String title = getIssueTitle(issue);
			message.setTitle(title);
			Journal lastJournal = journalService.getLastJournal(issue.getId());
			String content = getIssueContent(issue, lastJournal);
			message.setContent(content);

			message.setMessageType(MessageType.BUSINESS.getCode());
			message.setPriority(issue.getPriorityId().intValue());
			message.setSendMethod(1);
			message.setTargetType(TargetType.USER.getCode());
			message.setTargetIds(targetIds);// String.valueOf(assignedToId)
			String targetNames = "";
			message.setTargetNames(targetNames);
			message.setStatus(1);
			message.setSenderId(Administrator.getUserId());
			message.setSenderName(Administrator.getUserName());
			message.setSendTime(DateUtils.curLocalDateTime());

			result = sendMessageByTemplate(message);
		}
		return result;
	}

	private String getIssueTitle(Issue issueInfo) {
		StringBuffer titleBuffer = new StringBuffer();
		titleBuffer.append("[");
		titleBuffer.append(issueInfo.getProjectName());
		titleBuffer.append(" - ");
		titleBuffer.append(issueInfo.getTrackerName());
		titleBuffer.append(" #" + issueInfo.getId());
		titleBuffer.append("] ");
		titleBuffer.append(issueInfo.getSubject());
		return titleBuffer.toString();
	}

	private String getIssueContent(Issue issueInfo, Journal journal) {
		StringBuilder content = new StringBuilder();
		content.append("<div class=\"mail-detail-content\"><div class=\"qmbox\" style=\"min-height: 436px;\">");
		content.append("<style>.qmbox a:link {color:#169}");
		content.append(".qmbox a:visited {color:#169}");
		content.append(".qmbox a:hover {color:#c61a1a}");
		content.append(".qmbox a:active {color:#c61a1a}");
		content.append("</style>");

		content.append("<span class=\"header_F69W_0\"></span>");

		if (journal == null) {// 提交
			content.append("问题 <a href=\"/project/issue/" + issueInfo.getId()
					+ "\" style=\"color:#169\" target=\"_blank\" rel=\"noopener noreferrer\">#");
			content.append(issueInfo.getId());
			content.append("</a> 已由 ");
			content.append(issueInfo.getAuthorName() != null ? issueInfo.getAuthorName() : "管理员");
			content.append(" 提交。");
			content.append("<hr style=\"width:100%;height:1px;background:#ccc;border:0;margin:1.2em 0\">");
		} else {// 变更
			Long updatedById = journal.getUpdatedById();
			User user = commonService.getUserInfo(updatedById);
			String updateUserName = user != null ? user.getUserName()
					: updatedById != null && updatedById == 1L ? "管理员" : "";

			content.append("问题 <a href=\"/project/issue/" + issueInfo.getId()
					+ "\" style=\"color:#169\" rel=\"noopener noreferrer\">#");
			content.append(issueInfo.getId());
			content.append("</a> 已由 ");
			content.append("<a>" + updateUserName + "</a>");
			content.append(" 更新。");

			long journalId = journal.getId();
			List<JournalDetail> detailList = journalDetailService.findListByJournalId(journalId);
			content.append("<ul class=\"details\" style=\"margin-top: 10px;\">");
			detailList.forEach(detail -> {
				String showDetail = journalDetailService.showDetail(detail);
				content.append("<li style=\"margin-bottom: 4px;\">" + showDetail + "</li>");
			});
			content.append("</ul>");
			content.append("<div class=\"wiki journal-notes\">" + journal.getNotes() + "</div>");

			content.append("<hr style=\"width:100%;height:1px;background:#ccc;border:0;margin:1.2em 0\">");
		}

		content.append(
				"<h1 style=\"font-family:'Trebuchet MS', Verdana, sans-serif;margin:0px;font-size:1.5em;line-height:1.4em;font-weight: 500;\">");
		content.append("<a href=\"/project/issue/" + +issueInfo.getId()
				+ "\" style=\"color:#169\" rel=\"noopener noreferrer\">");
		content.append(issueInfo.getTrackerName());
		content.append(" #" + issueInfo.getId());
		content.append(": " + issueInfo.getSubject());
		content.append("</a></h1>");

		content.append("<ul class=\"details_snYo_2\" style=\"color:#959595;margin-bottom:1.5em\">");
		content.append("<li><strong>作者: </strong>");
		content.append(issueInfo.getAuthorName() != null ? issueInfo.getAuthorName() : "");
		content.append("</li>");
		content.append("<li><strong>状态: </strong>");
		content.append(issueInfo.getStatusName() != null ? issueInfo.getStatusName() : "新建");
		content.append("</li>");
		content.append("<li><strong>优先级: </strong>");
		content.append(issueInfo.getPriorityName() != null ? issueInfo.getPriorityName() : "普通");
		content.append("</li>");
		content.append("<li><strong>指派给: </strong>");
		content.append(issueInfo.getAssignedToName() != null ? issueInfo.getAssignedToName() : "未指派");
		content.append("<li><strong>领取人: </strong>");
		content.append(issueInfo.getRecipient() != null ? issueInfo.getRecipientName() : "无");
		content.append("</li>");
		content.append("<li><strong>分类: </strong>");
		content.append(issueInfo.getCategoryName() != null ? issueInfo.getCategoryName() : "");
		content.append("</li>");
		content.append("<li><strong>目标版本: </strong>");
		content.append(issueInfo.getFixedVersionId() != null ? issueInfo.getFixedVersionId().toString() : "");
		content.append("</li></ul>");

		if (issueInfo.getDescription() != null && !issueInfo.getDescription().isEmpty()) {
			content.append("<div style=\"padding-left: 1em;\">");
			content.append(issueInfo.getDescription());
			content.append("</div>");
		}

//		content.append("<hr style=\"width:100%;height:1px;background:#ccc;border:0;margin:1.2em 0\">");
		content.append("</div></div>");

		return content.toString();
	}
}